"""
数据模型基类
"""
from sqlalchemy import Column, Integer, DateTime, func
from sqlalchemy.ext.declarative import declared_attr
from core.database import Base


class BaseModel(Base):
    """数据模型基类"""
    __abstract__ = True
    
    @declared_attr
    def __tablename__(cls):
        # 自动生成表名（类名转下划线格式）
        import re
        return re.sub(r'(?<!^)(?=[A-Z])', '_', cls.__name__).lower()
    
    id = Column(Integer, primary_key=True, index=True, comment="主键ID")
    created_at = Column(
        DateTime(timezone=True), 
        server_default=func.now(), 
        comment="创建时间"
    )
    updated_at = Column(
        DateTime(timezone=True), 
        server_default=func.now(), 
        onupdate=func.now(), 
        comment="更新时间"
    )
    
    def to_dict(self):
        """转换为字典"""
        return {
            column.name: getattr(self, column.name)
            for column in self.__table__.columns
        }
    
    def __repr__(self):
        return f"<{self.__class__.__name__}(id={self.id})>"